<template>
  <transition-group
      tag="div"
      class="barrage-screen"
      @before-enter="beforeEnter"
      @enter="enter"
      appear
      @leave="level"
  >
    <div v-for="item in screenData"
      :key="item.time"
      :class="[item.size, 'time_' + item.time]"
      :style="{ backgroundColor: item.color }"
    >
      <el-image :src="item.avatarImg" draggable="false" class="barrageImg"/>
      <span>{{ item.name ? item.name : '无名氏'  }}{{'说: ' +item.content}}</span>
    </div>
  </transition-group>
</template>

<script setup>
import { ref } from "vue";
// 弹幕集合
let screenData = ref([]);
let screenIndex=0;

/** 增加弹幕 */
function addBarrage(barrageData){
  screenData.value.push(barrageData);
}

/** 进入前 */
function beforeEnter (el) {
  if(screenIndex <= screenData.value.length - 1){
    screenIndex++;
  }else {
    screenIndex = screenData.value.length - 1;
  }

  el.style.top = 24 * screenIndex % document.body.offsetWidth + "px";
  el.style.left = "100%";

  // 弹幕随机时间
  let roundTime = Math.random()*(5)+5;
  el.style.transition = roundTime.toFixed(2) + "s linear";
}

/** 进入 */
function enter (el) {
  el.offsetLeft;
  el.style.left = -(el.offsetWidth + 10) + "px";
  // 首个空格的下标位置
  let spaceIndex = el.style.transition.indexOf(' ');
  // 首个s的下标位置
  let sIndex = el.style.transition.indexOf('s');
  let barrageTime = el.style.transition.substring(spaceIndex+1,sIndex) * 1000;
  setTimeout(() => {
    let time = 0;
    // 获取当前的时间值
    el.classList.forEach(v => {
      if (v.indexOf("time_") === 0) {
        time = parseInt(v.substring(5));
      }
    });
    // 将这个值从对象里面给他去除掉
    screenData.value.some((v, i) => {
      if (time === v.time) {
        screenData.value.splice(i, 1);
        return true;
      }
    });
    el.style.transition = "none";
  }, barrageTime);
}

// 弹幕离开了
function level(el){

}
//暴露方法 必须暴露别人才能获取得到
defineExpose({
  addBarrage
})
</script>

